package com.ruoyi.common.utils.ps2;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class ExcelSplitter {
    // 配置参数
    private static final String INPUT_FILE = "C:\\Users\\xinhuiRong\\Desktop\\新建文件夹\\人物属性.xlsx";
    private static final String OUTPUT_DIR = "H:\\person表格";
    private static final int BATCH_SIZE = 1000;

    public static void main(String[] args) {
        try {
            // 创建输出目录
            Path outputPath = Paths.get(OUTPUT_DIR);
            if (!Files.exists(outputPath)) {
                Files.createDirectories(outputPath);
                System.out.println("创建输出目录: " + outputPath.toAbsolutePath());
            }

            // 读取原始Excel文件
            try (InputStream is = new FileInputStream(INPUT_FILE);
                 Workbook workbook = new XSSFWorkbook(is)) {

                Sheet originalSheet = workbook.getSheetAt(0); // 读取第一个Sheet

                // 获取表头
                Row headerRow = originalSheet.getRow(0);
                List<String> headers = new ArrayList<>();
                for (Cell cell : headerRow) {
                    headers.add(cell.getStringCellValue());
                }

                // 按A列的值范围分批处理
                int currentBatchStart = 0;
                int currentBatchEnd = BATCH_SIZE - 1;
                List<Row> batchRows = new ArrayList<>();

                for (int i = 1; i <= originalSheet.getLastRowNum(); i++) {
                    Row row = originalSheet.getRow(i);
                    if (row == null) continue;

                    Cell indexCell = row.getCell(0); // A列
                    if (indexCell == null || indexCell.getCellType() != CellType.NUMERIC) {
                        continue;
                    }

                    int indexValue = (int) indexCell.getNumericCellValue();

                    // 如果当前行不属于当前批次，先处理已收集的行
                    if (indexValue > currentBatchEnd) {
                        if (!batchRows.isEmpty()) {
                            createBatchFile(outputPath, headers, batchRows, currentBatchStart, currentBatchEnd);
                            batchRows.clear();
                        }

                        // 更新到下一个批次范围
                        currentBatchStart = (indexValue / BATCH_SIZE) * BATCH_SIZE;
                        currentBatchEnd = currentBatchStart + BATCH_SIZE - 1;
                    }

                    // 添加到当前批次
                    if (indexValue >= currentBatchStart && indexValue <= currentBatchEnd) {
                        batchRows.add(row);
                    }
                }

                // 处理最后一批
                if (!batchRows.isEmpty()) {
                    createBatchFile(outputPath, headers, batchRows, currentBatchStart, currentBatchEnd);
                }
            }

            System.out.println("分割完成！文件保存在: " + outputPath.toAbsolutePath());
        } catch (Exception e) {
            System.err.println("处理过程中出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 创建批次文件
     */
    private static void createBatchFile(Path outputPath, List<String> headers,
                                        List<Row> rows, int batchStart, int batchEnd) throws IOException {
        // 创建新工作簿
        try (Workbook newWorkbook = new XSSFWorkbook()) {
            Sheet newSheet = newWorkbook.createSheet("Sheet1");

            // 添加表头
            Row newHeaderRow = newSheet.createRow(0);
            for (int i = 0; i < headers.size(); i++) {
                newHeaderRow.createCell(i).setCellValue(headers.get(i));
            }

            // 添加数据行
            for (int i = 0; i < rows.size(); i++) {
                Row originalRow = rows.get(i);
                Row newRow = newSheet.createRow(i + 1);
                copyRow(originalRow, newRow);
            }

            // 保存文件
            String outputFileName = getOutputFileName(INPUT_FILE, batchStart, batchEnd);
            Path outputFilePath = outputPath.resolve(outputFileName);

            try (OutputStream os = new FileOutputStream(outputFilePath.toFile())) {
                newWorkbook.write(os);
            }

            System.out.println("已生成: " + outputFileName + " (包含 " + rows.size() + " 行数据)");
        }
    }

    /**
     * 复制行数据
     */
    private static void copyRow(Row sourceRow, Row targetRow) {
        for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
            Cell sourceCell = sourceRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell targetCell = targetRow.createCell(i);

            switch (sourceCell.getCellType()) {
                case STRING:
                    targetCell.setCellValue(sourceCell.getStringCellValue());
                    break;
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(sourceCell)) {
                        targetCell.setCellValue(sourceCell.getDateCellValue());
                    } else {
                        targetCell.setCellValue(sourceCell.getNumericCellValue());
                    }
                    break;
                case BOOLEAN:
                    targetCell.setCellValue(sourceCell.getBooleanCellValue());
                    break;
                case FORMULA:
                    targetCell.setCellFormula(sourceCell.getCellFormula());
                    break;
                default:
                    targetCell.setCellValue("");
            }

            // 复制单元格样式
            CellStyle newStyle = targetRow.getSheet().getWorkbook().createCellStyle();
            newStyle.cloneStyleFrom(sourceCell.getCellStyle());
            targetCell.setCellStyle(newStyle);
        }
    }

    /**
     * 生成输出文件名
     */
    private static String getOutputFileName(String originalName, int start, int end) {
        String baseName = originalName.replace(".xlsx", "");
        return String.format("%d-%d.xlsx",  start, end);
    }
}